package com.tiger.sendmessage.caspOpeapi;


import com.tiger.cache.RedisService;
import com.tiger.sendmessage.caspOpeapi.type.OpenApiConfig;
import com.tiger.sendmessage.caspOpeapi.type.TokenApiResult;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class Openapi {
    private final RedisService redisService;
    public final OpenApiConfig openApiConfig;
    private static String access_token;

    public Openapi(RedisService redisService, OpenApiConfig openApiConfig) {
        this.redisService = redisService;
        this.openApiConfig = openApiConfig;
    }

    @Async
    public void getAccessToken() {

        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("appSecret", openApiConfig.getAppSecret());

        HttpEntity entity = new HttpEntity<>(headers);
        TokenApiResult data = template.exchange(openApiConfig.getTokenUrl(), HttpMethod.GET, entity, TokenApiResult.class).getBody();
        System.out.println("-------------openaip toke--------------------");


        if(data != null && Objects.equals(data.getErrcode(), "0")) {
            access_token = data.getData();

            redisService.template.opsForValue().set("openapi_access_token", access_token);
        }
    }


    //代办事项
    public List<HashMap> taskList(String userId, int type) {
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);

        HashMap<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("pageSize", 1000);
        params.put("pageNumber", 1);
        params.put("userId", userId);


        HttpEntity entity = new HttpEntity<>(params, headers);



        try {
            HashMap<String, Object> data = template.exchange(openApiConfig.getTaskListUrl(), HttpMethod.POST, entity, HashMap.class).getBody();
            if(Objects.equals(data.get("errcode"), "0") && data.get("datas") != null) {
                return (List<HashMap>) data.get("datas");
            }else {
                System.out.println(data);
            }
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

    //获取单条代办详情
    public HashMap<String, Object> task(String userId, String taskWid) {
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);


        System.out.println("appId:" + openApiConfig.getAppId());
        System.out.println("accessToken:" + access_token);


        HashMap<String, Object> params = new HashMap<>();
        params.put("taskWid", taskWid);
        //params.put("taskId", taskWid);
        params.put("userId", userId);

        System.out.println("请求参数");
        System.out.println(params);

        System.out.println("接口地址");
        System.out.println(openApiConfig.getTaskUrl());

        HttpEntity entity = new HttpEntity<>(params, headers);



        HashMap<String, Object> data = template.exchange(openApiConfig.getTaskUrl(), HttpMethod.POST, entity, HashMap.class).getBody();

        System.out.println(data);


        if(Objects.equals(data.get("errcode"), "0") && data.get("data") != null) {
            return (HashMap<String, Object>) data.get("data");
        }

        return null;
    }


    //代办事项
    public List<HashMap> lastunTaskList(String userId) {
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);

        HashMap<String, Object> params = new HashMap<>();
        params.put("type", 1);
        params.put("pageSize", 10);
        params.put("pageNumber", 1);
        params.put("userId", userId);



        LocalDateTime now = LocalDateTime.now();
        // 计算前五分钟的时间
        LocalDateTime fiveMinutesAgo = now.minusSeconds(2 * 60 - 5);

        params.put("startTime", fiveMinutesAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        params.put("endTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));


        HttpEntity entity = new HttpEntity<>(params, headers);



        try {
            HashMap<String, Object> data = template.exchange(openApiConfig.getTaskListUrl(), HttpMethod.POST, entity, HashMap.class).getBody();
            if(Objects.equals(data.get("errcode"), "0") && data.get("datas") != null) {
                return (List<HashMap>) data.get("datas");
            }else {
                System.out.println(data);
            }
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return null;
    }


    //消息列表
    public List<HashMap> messageList(String userId, String appId) {
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);

        HashMap<String, Object> params = new HashMap<>();
        //params.put("deviceType", 0);
        params.put("pageSize", 1000);
        params.put("pageNumber", 1);
        params.put("userAccount", userId);
        params.put("isRead", 0);
        params.put("orderType", 1);

        if(appId != null && !appId.isEmpty()) {
            params.put("appId", appId);
        }

        HttpEntity entity = new HttpEntity<>(params, headers);


        try {

            HashMap<String, Object> data = template.exchange(openApiConfig.getMessageListUrl(), HttpMethod.POST, entity, HashMap.class).getBody();

            System.out.println(data);
            if(Objects.equals(data.get("code"), "0000") && data.get("data") != null) {
                HashMap<String, HashMap> r = (HashMap<String, HashMap>) data.get("data");
                return (List<HashMap>) r.get("result");
            }else {
                System.out.println(data);
            }

        }catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

    //未读消息
    public List<HashMap> unReadmessage(String userId) {

        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);

        HashMap<String, Object> params = new HashMap<>();
        params.put("pageSize", 20);
        params.put("pageNumber", 1);
        params.put("userAccount", userId);
        params.put("orderType", 1);
        //params.put("deviceType", 0);
        //params.put("isRead", 0);


        LocalDateTime now = LocalDateTime.now();
        // 计算前五分钟的时间
        LocalDateTime fiveMinutesAgo = now.minusSeconds(2 * 60 - 5);

        params.put("startTime", fiveMinutesAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        params.put("endTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));


        HttpEntity entity = new HttpEntity<>(params, headers);






        HashMap<String, Object> data = template.exchange(openApiConfig.getMessageListUrl(), HttpMethod.POST, entity, HashMap.class).getBody();


        if(Objects.equals(userId, "31100018")) {
            System.out.println(openApiConfig.getMessageListUrl());
            System.out.println(params);
            System.out.println(data);
        }
        if(Objects.equals(data.get("code"), "0000") && data.get("data") != null) {
            HashMap<String, HashMap> r = (HashMap<String, HashMap>) data.get("data");
            return (List<HashMap>) r.get("result");

        }

        return null;
    }


    //未读消息数量
    public int unReadmessageCount(String userId) {

        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);

        HashMap<String, Object> params = new HashMap<>();
        params.put("pageSize", 1);
        params.put("pageNumber", 1);
        params.put("userAccount", userId);
        params.put("deviceType", 0);
        params.put("isRead", 0);



        HttpEntity entity = new HttpEntity<>(params, headers);


        HashMap<String, Object> data = template.exchange(openApiConfig.getMessageListUrl(), HttpMethod.POST, entity, HashMap.class).getBody();

        if(Objects.equals(data.get("code"), "0000") && data.get("data") != null) {
            HashMap<String, Object> r = (HashMap<String, Object>) data.get("data");
            return (int) r.get("totalSize");

        }

        return 0;
    }


    //统一验证登录
    public String login(String username, String password) throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // 转换为字节
        byte[] dataBytes = password.getBytes(StandardCharsets.UTF_8);

        // 密钥和IV
        String keyString = openApiConfig.getAESKey(); // 密钥长度必须是16, 24或32字节，对应AES-128, AES-192, AES-256
        String ivString = openApiConfig.getAESIv();

        // 密钥和IV转换为字节
        Key key = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes(StandardCharsets.UTF_8));

        // 创建Cipher实例并设置为加密模式
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        // 加密数据
        byte[] encryptedBytes = cipher.doFinal(dataBytes);

        // 将加密后的数据转换为Base64编码
        String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedBytes);


        RestTemplate template = new RestTemplate();

        // 准备请求数据
        MultiValueMap<String, String> postParams = new LinkedMultiValueMap<>();
        postParams.add("username", username);
        postParams.add("service", openApiConfig.getService());
        postParams.add("password", encryptedBase64);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("appId", openApiConfig.getAppId());
        headers.add("accessToken", access_token);

        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(postParams, headers);

        HashMap<String, Object> data = template.exchange(openApiConfig.getLoginUrl(), HttpMethod.POST, entity, HashMap.class).getBody();

        return ((ArrayList<String>) data.get("uid")).get(0);
    }



}
